#pragma once
#include <iostream>
#include "nocopy.hpp"
#include <string>
#include <cstdint> //uint16_t
#include <vector>

#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <strings.h> //bzero

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

#include <pthread.h>
// #include <mutex>
// #include <condition_variable>  c++
static const std::string default_ip = "0.0.0.0"; //static 各个cpp文件中独立一份
static const uint16_t default_port = 8888;

static const int default_sockfd = -1;

using task_t = std::function<void()>;

class UdpServer : public nocopy 
{
public:
    UdpServer( uint16_t port = default_port)
        :_port(port), _sockfd(default_sockfd)
    {
        pthread_mutex_init(&_users_mutex, nullptr);
    }
    void Init()
    {
        //1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)  //致命错误
        {
            lg.LogMessage(Fatal, "socket error, %d : %s\n", errno, strerror(errno));
            exit(sockfd_err);
        }
        // std::cout << "211";

        lg.LogMessage(Info, "socket created, sockfd: %d\n", _sockfd);
        // lg.LogMessage(Info, "socket created, sockfd: %s\n", std::to_string(_sockfd)); //Debug  日志有问题，%s打不出来
                    //没问题，%s,这里要是const char*才行，加一个c_str()即可
        //2. 绑定
        // std::cout << "211" << std::endl; //注意：不打印\n，这个测试语句其实没有作用

        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);

        int ok = ::bind(_sockfd, (const struct sockaddr*)&local, sizeof local);
        if(ok == -1)
        {
            lg.LogMessage(Fatal, "bind error, %d : %s\n", errno, strerror(errno));
            exit(bind_err);
        }

        std::cout << "准备创建" << std::endl; //debug
        ThreadPool<task_t>::GetInstance()->Start();     //创建线程池
    }
    void AddUsers(InetAddr&& user)
    {
        LockGuard lock(&_users_mutex);
        for(auto& e : _users)       //判断是否已经存在
            if(e == user) return;

        _users.push_back(user);   
        lg.LogMessage(Debug, "new user: %s\n", user.PrintDebug().c_str());      //new加进去了，但是转发不了
    }
    void Route(const std::string& msg)
    {
        LockGuard lock(&_users_mutex);
        for(auto& user : _users)
        {
            lg.LogMessage(Debug, "is send user: %s\n", user.PrintDebug().c_str());      //这也是没问题，找到了，客户端不对
            sendto(_sockfd, msg.c_str(), msg.size(), 0, 
                (const struct sockaddr*)&user.GetAddr(), sizeof user.GetAddr());
        }
    }
    void Start()
    {
        char buffer[1024];  
        while(1)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int n = recvfrom(_sockfd, buffer, 1023, 0, (struct sockaddr*)&peer, &len);

            if(n > 0)
            {
                buffer[n] = 0;
                std::string str = buffer;
                str = InetAddr(peer).PrintDebug() + "# " + str;
                AddUsers(InetAddr(peer));       //添加用户
                task_t task = std::bind(&UdpServer::Route, this, str);
                ThreadPool<task_t>::GetInstance()->Push(task);
            }
        }
    }
    ~UdpServer()
    {
        pthread_mutex_destroy(&_users_mutex);
    }
private:
    uint16_t _port;
    int _sockfd;

    std::vector<InetAddr> _users; //56.23
    pthread_mutex_t _users_mutex;
};
